package com.atstudying.mall.order.service.impl;

import com.atstudying.common.exception.NoStockException;
import com.atstudying.common.utils.PageUtils;
import com.atstudying.common.utils.Query;
import com.atstudying.common.utils.R;
import com.atstudying.common.vo.MemberRespVo;
import com.atstudying.mall.order.constant.OrderConstant;
import com.atstudying.mall.order.dao.OrderDao;
import com.atstudying.mall.order.entity.OrderEntity;
import com.atstudying.mall.order.entity.OrderItemEntity;
import com.atstudying.mall.order.enume.OrderStatusEnum;
import com.atstudying.mall.order.feign.CartFeignService;
import com.atstudying.mall.order.feign.MembersFeignService;
import com.atstudying.mall.order.feign.ProductFeignService;
import com.atstudying.mall.order.feign.WareFeignService;
import com.atstudying.mall.order.interceptor.OrderInterceptor;
import com.atstudying.mall.order.service.OrderItemService;
import com.atstudying.mall.order.service.OrderService;
import com.atstudying.mall.order.to.OrderCreateTo;
import com.atstudying.mall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal=new ThreadLocal<>();
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    MembersFeignService membersFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 给订单确认页返回需要的数据confirm
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() {

        OrderConfirmVo confirmVo = new OrderConfirmVo();

        //使用拦截器里面的threalocal
        MemberRespVo memberRespVo = OrderInterceptor.loginUser.get();

        System.out.println("主线程。。。"+Thread.currentThread().getId());
        System.out.println("memberRespVo的id。。。"+memberRespVo.getId());

        //得到/addtTocart的请求进来的头数据（获取之前的请求）
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getaddress = CompletableFuture.runAsync(() -> {
            System.out.println("address线程。。。"+Thread.currentThread().getId());

            //每一个线程都来共享之前的数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1：远程查询所有的收货地址列表。。。远程调用查询收货地址ums_member_receive_address表  mall-member
            System.out.println("memberRespVo的id。。。"+memberRespVo.getId());

            List<MemberAddressVo> address = membersFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);

        }, executor);

        CompletableFuture<Void> getcurrentUserCartItem = CompletableFuture.runAsync(() -> {
            //每一个线程都来共享之前的数据

            System.out.println("currentUserCartItem线程。。。"+Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);

            //2：远程查询购物车所有选中的购物项 mall-order
            List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
            confirmVo.setItems(currentUserCartItem);

        }, executor).thenRunAsync(()->{

            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wareFeignService.getSkusHasStock(collect);
            List<SkuHasStockVo> data = hasStock.getData("data", new com.alibaba.fastjson.TypeReference<  List<SkuHasStockVo> >() {
            });
            if (data!=null){
                Map<Long, Boolean> collect1 = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setStocks(collect1);

            }

        },executor);

        CompletableFuture<Void> getintegration = CompletableFuture.runAsync(() -> {
            //每一个线程都来共享之前的数据

            RequestContextHolder.setRequestAttributes(requestAttributes);

            //3：查询用户积分
            Integer integration = memberRespVo.getIntegration();
            confirmVo.setInteger(integration);

        }, executor);

        //5：todo 防重令牌

        String token = UUID.randomUUID().toString().replace("-", "");

        //todo 给redis，confirmvo设置防重令牌
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        try {
            //Returns a new CompletableFuture that is completed when all of
            //     * the given CompletableFutures complete.  If any of the given
            //     * CompletableFutures complete exceptionally, then the returned
            //     * CompletableFuture also does so, with a CompletionException
            //     * holding this exception as its cause.
            CompletableFuture.allOf(getaddress,getintegration,getcurrentUserCartItem).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //4：一些其他数据


        return confirmVo;
    }

    //高并发场景
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {

        confirmVoThreadLocal.set(vo);
        SubmitOrderResponseVo submitOrderResponseVo=new SubmitOrderResponseVo();
        //使用拦截器里面的threalocal
        MemberRespVo memberRespVo = OrderInterceptor.loginUser.get();
        //1：验证令牌【令牌的对比和删除，获取令牌必须保证原子性】
        //如果redis调用get方法获取KEYS[1]值，然后它就会返回令牌删除，然后返回0
        //0令牌对比不一样就删除失败 1令牌对比删除成功
        String script="if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子令牌验证和删除
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result==0){
            //令牌验证不通过
            submitOrderResponseVo.setCode(1);

            return submitOrderResponseVo;
        }else {
            //令牌验证通过
//        下单：去创建订单，验证令牌，验证价格，锁库存

            //第一步：创建订单，订单项等信息
            OrderCreateTo order=createOrder();
            //第二步：验证价格
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            //前端传来的页面的值和后端我们计算的价格这两个值相差不可以大于0.1；；就是会有误差很正常
            if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.1){
                //金额对比..

                // todo 第三步：保存订单
                saveOrder(order);
                //todo 第四步：远程库存锁定  我们现在要加一个事务（只要有异常回滚订单数据） 只要订单一保存成功，我们马上就要锁住库存，如果库存没锁住就会回调返回失败
                //订单号，所有订单项（skuId,skuName,num）
                WareSkuLockVo lockVo=new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                //去（mall-ware)库存服务锁住我们在mall-order中传递过来的lockVo
                //为了保证高并发。库存服务可以自己回滚。可以发消息给库存服务
                //库存服务本身也可以使用自动解锁模式
                R r = wareFeignService.orderLockStock(lockVo);
                if (r.getCode()==0){
                    //锁成功
                    submitOrderResponseVo.setOrderEntity(order.getOrder());
                    //todo 远程扣减积分
//                    int i=10/0;//订单回滚，库存不滚
                    return submitOrderResponseVo;
                }else {
                    //锁失败
                    throw new  NoStockException();
//                    submitOrderResponseVo.setCode(3);
//                    return submitOrderResponseVo;
                }

            }else {
                submitOrderResponseVo.setCode(2);
                return submitOrderResponseVo;
            }

        }
//        String redistoken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        if (orderToken!=null&&orderToken.equals(redistoken)){
//            //令牌验证通过
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//            return null;
//        }else {
//            //不通过
//            return null;
//        }
//        return submitOrderResponseVo;

    }

    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {

        OrderEntity orderEntity=order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);


    }

    private OrderCreateTo createOrder( ){

        OrderCreateTo createTo = new OrderCreateTo();
        //1：生成一个订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        //2：获取到所有的订单项
        List<OrderItemEntity> itemEntities = builderOrderItems(orderSn);

        //3：验价（计算价格相关）
        computePrice(orderEntity,itemEntities);

        createTo.setOrderItems(itemEntities);
        createTo.setOrder(orderEntity);
        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {

        BigDecimal total = new BigDecimal("0.0");
        //订单总额，叠加每一个订单项的总额信息
        BigDecimal coupon=new BigDecimal("0.0");
        BigDecimal integration=new BigDecimal("0.0");
        BigDecimal promotion=new BigDecimal("0.0");
        BigDecimal growth=new BigDecimal("0.0");
        BigDecimal gift=new BigDecimal("0.0");

        //订单的总额，叠加每一个订单的总额信息
        for (OrderItemEntity entity:itemEntities
             ) {
            BigDecimal realAmount = entity.getRealAmount();
            coupon=coupon.add(entity.getCouponAmount());
            integration=integration.add(entity.getIntegrationAmount());
            promotion=promotion.add(entity.getPromotionAmount());
            total=total.add(realAmount);
            //设置积分，成长值
            gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }
        //1：订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }

    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setOrderSn(orderSn);
        //获取收货地址的信息
        //使用ThreadLocal皆可以使用一条线程获取数据
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        R fare = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fareresp = fare.getData("data", new com.alibaba.fastjson.TypeReference<FareVo>() {
        });

        //设置运费信息
        orderEntity.setFreightAmount(fareresp.getFare());

        //设置收货人信息
        orderEntity.setReceiverCity(fareresp.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareresp.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareresp.getAddress().getName());
        orderEntity.setReceiverPhone(fareresp.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareresp.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareresp.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareresp.getAddress().getRegion());

        //设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    /**
     * 构建所有订单项数据
     * @return
     * @param orderSn
     */
    private List<OrderItemEntity> builderOrderItems(String orderSn){
        //2：获取到所有的订单项（创建订单项）
        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        if (currentUserCartItem!=null&&currentUserCartItem.size()>0){
            List<OrderItemEntity> itemEntities = currentUserCartItem.stream().map(cartItems -> {
                OrderItemEntity itemEntity = builderOrderItem(cartItems);

                itemEntity.setOrderSn(orderSn);

                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建所有订单项中的每一个订单项
     * @param cartItem
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1：订单信息，订单号
        
        //2：商品的spu信息
        Long skuId = cartItem.getSkuId();
        R spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = spuInfoBySkuId.getData("data", new com.alibaba.fastjson.TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuBrand(data.getBrandId().toString());
        orderItemEntity.setSpuId(data.getId());
        orderItemEntity.setSpuName(data.getSpuName());
        orderItemEntity.setCategoryId(data.getCatalogId());

        //3：商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = org.springframework.util.StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());

        //4：优惠信息（不做）
        
        //5：积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6：订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal(("0")));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额=总额减去各种优惠
        BigDecimal orign = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);



        return orderItemEntity;
    }

}